#include <jni.h>
#include "Joystick.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_Joystick_eventos(JNIEnv *env, jobject obj){
	int fd, rc;
	int done = 0;

	jint valor1;
	jshort valor2;
	jint valor3;
	jint valor4;
	jint flag;

	struct js_event jse;
	
		
		fd = open_joystick();
			if (fd < 0)
			{
				printf("open failed.\n");
				exit(1);
			}
	jclass clase = (*env)->GetObjectClass(env,obj);
	jfieldID fieldIDtime = (*env)->GetFieldID(env,clase,"time","I");
	jfieldID fieldIDvalue = (*env)->GetFieldID(env,clase,"value","S");
	jfieldID fieldIDtype = (*env)->GetFieldID(env,clase,"type","I");
	jfieldID fieldIDnumber = (*env)->GetFieldID(env,clase,"number","I");
	jfieldID fieldIDflag = (*env)->GetFieldID(env,clase,"flag","I");
	if (fieldIDtime == NULL)
		return; // Excepcion lanzada

	if(fieldIDvalue == NULL)
		return;

	if(fieldIDtype == NULL)
		return;

	if(fieldIDnumber == NULL){
		printf("No esta el campo number\n");
		return;
	}

	valor1 = (*env)->GetIntField(env,obj,fieldIDtime);
	valor2 = (*env)->GetShortField(env,obj,fieldIDvalue);
	valor3 = (*env)->GetIntField(env,obj,fieldIDtype);
	valor4 = (*env)->GetIntField(env,obj,fieldIDnumber);
	flag = (*env)->GetIntField(env,obj,fieldIDflag);


	if(fd<0)
	{
		flag = 1;
		(*env)->SetIntField(env,obj,fieldIDflag,flag);
	}else
	{
		while (!done) {
			rc = read_joystick_event(&jse);
	        	usleep(1000);
	        	if (rc == 1)
	        	{

	        		valor1 = jse.time;
	        		valor2 = jse.value;
	        		valor3 = (int)jse.type;
	       			valor4 = (int)jse.number;

				if(valor3==1){
	       				(*env)->SetIntField(env,obj,fieldIDtime,valor1);
	       				(*env)->SetShortField(env,obj,fieldIDvalue,valor2);
	       				(*env)->SetIntField(env,obj,fieldIDtype,valor3);
	       				(*env)->SetIntField(env,obj,fieldIDnumber,valor4);
				}
	        }
		}
	}
return;
}
